/*
 * Copyright (c) 2021-present, the hapjs-platform Project Contributors
 * SPDX-License-Identifier: Apache-2.0
 */

import $fetch from '@system.fetch'
import $utils from './utils'
import storage from '@system.storage'
import prompt from '@system.prompt'
Promise.prototype.finally = function (callback) {
  const P = this.constructor
  return this.then(
    (value) => P.resolve(callback()).then(() => value),
    (reason) =>
      P.resolve(callback()).then(() => {
        throw reason
      })
  )
}
function requestHandle(params) {
  return new Promise((resolve, reject) => {
    storage.get({
      key: 'token',
      success: async function (data) {
        const token = data;
        prompt.showToast({
          message: '数据请求中。。。'
        })
        try {
          const response = await $fetch.fetch({
            url: params.url,
            method: params.method,
            data: params.data,
            header: {
              Authorization: token ? `Bearer ${token}` : null,
              ...params.header
            }
          });

          console.log(response, 'response');
          const result = response.data;
          const content = JSON.parse(result.data);
          console.log(content);
          /* @desc: 可跟具体不同业务接口数据，返回你所需要的部分，使得使用尽可能便捷 */
          // content.success ? resolve(content.data) :
          resolve(content);
        } catch (error) {
          console.log(`🐛 request fail, code = ${error.code}`);
          reject(error);
        } finally {
          console.log(`✔️ request @${params.url} has been completed.`);
        }
      },
      fail: function (data, code) {
        console.log(`handling fail, code = ${code}`);
        reject(new Error(`Failed to get token, code = ${code}`));
      }
    });
  });
}


function twoRequestHandle(params,token) {
  return new Promise((resolve, reject) => {

    console.log(token, 'token');
    $fetch
      .fetch({
        url: params.url,
        method: params.method,
        data: params.data,
        header: {
          Authorization: token ? `Bearer ${token}` : null,
          ...params.header
        }
      })
      .then((response) => {
        console.log(response, 'response');
        const result = response.data
        const content = JSON.parse(result.data)
        console.log(content);
        /* @desc: 可跟具体不同业务接口数据，返回你所需要的部分，使得使用尽可能便捷 */
        //content.success ? resolve(content.data) :
        resolve(content)
      })
      .catch((error, code) => {
        console.log(`🐛 request fail, code = ${code}`)
        reject(error)
      })
      .finally(() => {
        console.log(`✔️ request @${params.url} has been completed.`)
        resolve()
      })
  })
}
export default {
  postForm: function (url, params) {
    console.log(url,params);
    return requestHandle({
      method: 'post',
      url: url,
      data: params,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
    })
  },
  postJson: function (url, params) {
    return requestHandle({
      method: 'post',
      url: url,
      data: params,
      header: {
        'Content-Type': 'application/json'
      },
    })
  },
  post: function (url, params) {
    return requestHandle({
      method: 'post',
      url: url,
      data: params,
    })
  },
  get: function (url, params) {
    return requestHandle({
      method: 'get',
      url: $utils.queryString(url, params),
    })
  },
  put: function (url, params) {
    return requestHandle({
      method: 'put',
      url: url,
      data: params,
    })
  },
  // 如果，method 您需要更多类型，可自行添加更多方法；
}
